<template>
  <div class="app-container">
    <el-button
      v-if="permission"
      type="primary"
      icon="el-icon-plus"
      style="margin-bottom:20px;"
      @click="handleAdd"
    >新增基地</el-button>
    <my-table
      :base-list="baseList"
      :list-loading="listLoading"
      @modify="handleModify"
      @delete-site="deleteSite"
    />
    <my-dialog
      :dialog-status="dialogStatus"
      :temp="temp"
      :dialog-form-visible="dialogFormVisible"
      :ent-select="entSelect"
      :click-dialog="clickDialog"
      @add-data="addData"
      @modify-data="modifiedData(row)"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  queryBase,
  modifiedBase,
  delPlantation
} from '@/api/base'
import { queryEnterprise, getAllEnterprise } from '@/api/enterprise'
import { getLngLat } from '@/api/geoCode'
import MyTable from './components/MyTable'
import MyDialog from './components/MyDialog'
import store from '@/store'

export default {
  name: 'BaseItem',
  components: {
    MyTable,
    MyDialog
  },
  data() {
    return {
      tableKey: 0,
      baseList: [],
      entList: [],
      entSelect: [],
      clickDialog: false,
      listLoading: true,
      listQuery: {
        account: store.getters.token
      },
      temp: {
        siteName: '',
        square: undefined,
        province: '安徽省',
        city: '合肥市',
        county: '蜀山区',
        location: '',
        remarks: '',
        entId: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      role: Number.parseInt(store.getters.role)
    }
  },
  computed: {
    // ...mapGetters([
    //   'role'
    // ]),
    permission() {
      return this.role === 0 || this.role === 4
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      if (this.role === 0) {
        this.getAllEnterprise()
      } else if (this.role === 4) {
        this.queryEnts()
      } else {
        this.getBase()
      }
      // this.getBase()
    },
    async queryEnts() {
      const res = await queryEnterprise({
        account: store.getters.token,
        limit: -1,
        page: -1
      })
      console.log(1, res)
      this.entList = res.enterprise
      this.entSelect = this.entList.map(item => {
        return {
          label: item.entName,
          value: item.entId
        }
      })
      this.getBase()
    },
    async getAllEnterprise() {
      const res = await getAllEnterprise({
        limit: -1,
        page: -1
      })
      this.entList = res.enterprise
      this.entSelect = this.entList.map(item => {
        return {
          label: item.entName,
          value: item.entId
        }
      })
      this.getBase()
    },
    getBase() { // 根据传入的权限查找基地
      queryBase(this.listQuery)
        .then(response => {
          console.log(response)
          this.baseList = response.plantation
          const entsArr = response.enterprise
          this.baseList.map((item, index) => {
            // const index = this.entList.findIndex(i => {
            //   return i.entId === item.entId
            // })
            item.entName = entsArr[index].entName
          })
          this.listLoading = false
          // this.entList = res.enterprise
          // const res = new Map()
          // this.entSelect = this.entSelect.filter((a) => !res.has(a.value) && res.set(a.value, 1))
        })
        .catch(error => {
          console.log(error)
        })
    },
    resetTemp() {
      this.temp = {
        siteName: '',
        square: undefined,
        province: '安徽省',
        city: '合肥市',
        county: '蜀山区',
        location: '',
        remarks: '',
        entId: undefined
      }
    },
    handleAdd() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.clickDialog = !this.clickDialog
    },
    addData() {
      const temp = this.temp
      const keyWord = temp.province + temp.city + temp.county + temp.location
      getLngLat(keyWord)
        .then(async response => {
          const location = response.location
          await store.dispatch('base/setLocation', location)
          await store.dispatch('base/setTemp', temp)
          this.$router.push({
            path: '/base/create'
          })
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleModify(row) {
      this.temp = Object.assign({}, row)
      this.currentBaseId = row.siteId
      this.dialogStatus = 'modify'
      this.dialogFormVisible = true
      this.clickDialog = !this.clickDialog
    },
    modifiedData() {
      const tempData = Object.assign({}, this.temp)
      delete tempData.entId
      delete tempData.square
      tempData.siteId = this.currentBaseId
      modifiedBase(tempData).then(() => {
        const index = this.baseList.findIndex(v => v.entId === this.temp.entId)
        this.baseList.splice(index, 1, this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: '恭喜',
          message: '基地信息修改成功！',
          type: 'success',
          duration: 2000
        })
        this.$router.go(0)
      })
    },
    async deleteSite(siteId) {
      const res = await delPlantation({ siteId })
      if (res.flag) {
        const index = this.baseList.findIndex(item => {
          return item.siteId === siteId
        })
        this.baseList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功！'
        })
      }
    }
  }
}
</script>
